//
//  WBMainViewController.swift
//  YYLWeibo
//
//  Created by 楊亜玲 on 16/11/9.
//  Copyright © 2016年 楊亜玲. All rights reserved.
//

import UIKit

class WBMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildControllers()
        setupComposeButton()
        
    }
    
    // 设备横屏支持
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
    
    // 撰写按钮点击事件
    func composeBtnClicked() {
        print("composeBtnClicked")
    }
    
    // 懒加载控件
    lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add",backgroundImageName: "tabbar_compose_button")
    

}

extension WBMainViewController{
    // 设置撰写按钮
    func setupComposeButton(){
        tabBar.addSubview(composeButton)
        
        // 1. 设置按钮frame
        let count = CGFloat(childViewControllers.count)
        // 减少向内缩进宽度，让按钮宽度增大(2个容错点)，盖住容错点
        let marginW = tabBar.bounds.width / count - 1
        // !!!OC: CGRectInset (正数向内缩紧进，负数向外扩展)!!!
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * marginW, dy: 0)
        
        // 2.监听按钮点击
        composeButton.addTarget(self, action: #selector(composeBtnClicked), for: .touchUpInside)
    }

    
    // 创建所有子控制器
     func setupChildControllers() -> () {
        
        // 使用json格式文件设置控制器内容
        // 1>路径 2>加载NSData 3>反序列化转换成数组
        guard let path = Bundle.main.path(forResource: "main.json", ofType: nil),
            let data = NSData(contentsOfFile: path),
            let array = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [[String: Any]]
            else{
                return
        }
//        // 数据转换成plist
//        // 数组 －> json序列化
//        let jsonData = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        (jsonData as NSData).write(toFile: "/Users/youarei/Desktop/test.json", atomically: true)
        
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        viewControllers = arrayM
        
    }
    
    /// 使用字典创建一个子控制器
    private func controller(dict: [String: Any]) -> UIViewController {
        // 1.获取字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let visitorViewInfo = dict["visitorInfo"] as? [String: String],
            // ～！！反射加载类！！～
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type
            
            else {
                return UIViewController()
        }
        // 2.创建视图控制器
        let vc = cls.init()
        vc.title = title
        
        // 3.设置tabbar图标(
        vc.tabBarItem.image = UIImage(named:"tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named:"tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        // 4.设置tabbar标题字体（选中颜色、大小)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .selected)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 14)], for: UIControlState(rawValue:0))
        
        // 5.设置访客视图信息
        vc.visitorViewDict = visitorViewInfo
        
        
        
        let nav = WBNavigationController(rootViewController: vc)
        
        return nav
    }
}
